from django.http import JsonResponse

from calc.models import Server
from system.models import Manager
from django.http import HttpResponse
from system.models import Department
from django.core import serializers
from common.page_util import page_util, page_low_util
from common.token import generate_token
import json


def login(request):
    data = json.loads(request.body)
    response = {}
    try:
        m = Manager.objects.get(username=data['username'])
    except Exception:
        print(Exception)
        response['code'] = 400
        response['msg'] = "无此用户"
        return JsonResponse(response)
    if m.password == data['password']:
        response['token'] = generate_token(m.username)
        response['status'] = 200
        response['msg'] = "登陆成功"
        m.password = ''
        response['user_info'] = m.toJSON()
        return JsonResponse(response)
    else:
        response['code'] = 400
        response['msg'] = "密码错误"
        return JsonResponse(response)


def logout(request):
    response = {}
    try:
        del request.session['member_id']
    except KeyError:
        pass
    response['code'] = 200
    response['msg'] = "登陆成功"
    return JsonResponse(response)
